package com.jues.huichain.login.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.InputType;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.RegexUtils;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxCompoundButton;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jues.huichain.R;
import com.jues.huichain.R2;
import com.jues.huichain.login.presenter.LoginPresenter;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import health.lm.com.component_base.base.mvp.activity.XActivity;
import health.lm.com.component_base.helper.ImageLoaderHelper;
import health.lm.com.component_base.util.TimerHelper;
import health.lm.com.data.App;
import health.lm.com.router.ARouterConstant;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function4;

/**
 * 登录
 */
@Route(path = ARouterConstant.LoginActivity)
public class LoginActivity extends XActivity<LoginPresenter> {
    //@BindView(R2.id.et_phone)
    EditText etPhone;
    //@BindView(R2.id.et_code)
    EditText etCode;
    @BindView(R2.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R2.id.ll_phone)
    LinearLayout llPhone;
    //@BindView(R2.id.et_username)
    EditText etUsername;
    //@BindView(R2.id.et_psw)
    EditText etPsw;
    @BindView(R2.id.ll_username)
    LinearLayout llUsername;
    @BindView(R2.id.tv_login)
    TextView tvLogin;
    @BindView(R2.id.tv_forget_psw)
    TextView tvForgetPsw;
    @BindView(R2.id.tv_register)
    TextView tvRegister;
    @BindView(R2.id.iv_login_logo)
    ImageView iv_login_logo;
    @Autowired
    Bundle jumpBundle;
    @Autowired
    String jumpPath;
    @BindView(R2.id.pwdLogin)
    RadioButton pwdLogin;
    @BindView(R2.id.phoneLogin)
    RadioButton phoneLogin;
    @BindView(R2.id.rg_login_type)
    RadioGroup rgLoginType;
    //@BindView(R2.id.cb_pwd)
    CheckBox cbPwd;
    @BindView(R2.id.tv_agreement)
    TextView mTvAgreement;
    private CountDownTimer mTimerHelper;

    private boolean isUserName = true;
    private ScaleAnimation sato0 = new ScaleAnimation(1, 0, 1, 1,
            Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.5f);
    private RadioGroup.OnCheckedChangeListener listen = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (R.id.phoneLogin == group.getCheckedRadioButtonId()) {
                if (isUserName) llUsername.startAnimation(sato0);
            } else if (R.id.pwdLogin == group.getCheckedRadioButtonId()) {
                llPhone.startAnimation(sato0);
            }
        }
    };
    private ScaleAnimation sato1 = new ScaleAnimation(0, 1, 1, 1,
            Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.5f);
    private long mExitTime;

    @Override
    protected void setImmersionBar() {
        mImmersionBar.transparentBar().statusBarDarkFont(true).init();
    }

    @SuppressLint("CheckResult")
    protected void initWidget() {
        ImageLoaderHelper.getInstance().load(mActivity, App.getModel().getCoin_url(), iv_login_logo);
        //跳转注册页面
        RxView.clicks(tvRegister)
                .compose(bindToLife())
                .subscribe(o -> gotoActivity(ARouterConstant.RegisterActivity));
        //平台协议
        RxView.clicks(mTvAgreement).compose(bindToLife())
                .subscribe(o -> {
                    withValueActivity(ARouterConstant.InfoWebviewActivity)
                            .withString(ARouterConstant.TOPBAR_TITLE, "平台协议")
                            .withInt(ARouterConstant.TYPE, ARouterConstant.REGISTER)
                            .navigation();
                    //ARouter.getInstance().build(ARouterConstant.SimpleWebViewActivity)
                    //        .withString("url", App.model.getAgreement_url()).navigation();
                });
        //跳转到找回密码页面
        RxView.clicks(tvForgetPsw)
                .compose(bindToLife())
                .subscribe(o -> gotoActivity(ARouterConstant.FindPSWActivity));
        //密码显示明文
        RxCompoundButton.checkedChanges(cbPwd)
                .compose(bindToLife())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        etPsw.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    } else {
                        etPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    }
                });
        //登录类型
//        RxView.clicks(tvLoginType)
//                .compose(bindToLife())
//                .subscribe(o -> {
//                    if (isUserName) {
//                        llUsername.startAnimation(sato0);
//                    } else {
//                        llPhone.startAnimation(sato0);
//                    }
//                });
        //用户名输入监听
        RxTextView.textChangeEvents(etUsername)
                .compose(bindToLife())
                .subscribe(textViewTextChangeEvent -> etPsw.setText(""));
        //手机号输入监听
        RxTextView.textChangeEvents(etPhone)
                .compose(bindToLife())
                .subscribe(textViewTextChangeEvent -> etCode.setText(""));

        //获取验证码
        RxView.clicks(tvGetCode).subscribe(v -> {
            String phone = etPhone.getText().toString().trim();
            if (!RegexUtils.isMobileExact(phone)) {
                getvDelegate().toastShort("请输入正确的手机号");
            } else {
                getP().getCode(phone);
                mTimerHelper = TimerHelper.countDown(tvGetCode, 60000, 1000, "获取验证码");
            }
        });
//        //获取验证码
//        RxView.clicks(tvGetCode)
//                .compose(bindToLife())
//                .flatMap(o -> {
//                    String phone = etPhone.getText().toString().trim();
//                    if (!RegexUtils.isMobileExact(phone)) {
//                        getvDelegate().toastShort("请输入正确的手机号");
//                        return Observable.empty();
//                    } else {
//                        getP().getCode(phone);
//                        return Observable.just(true);
//                    }
//                })
//                .flatMap(aBoolean -> {
//                    RxView.enabled(tvGetCode).accept(false);
//                    RxTextView.text(tvGetCode).accept("重新发送(60)s");
//                    return Observable.interval(0, 1, TimeUnit.SECONDS, Schedulers.io())
//                            .take(60)
//                            .compose(bindToLife())
//                            .map(aLong -> 60 - (aLong + 1));
//                })
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(aLong -> {
//                    if (aLong == 0) {
//                        RxView.enabled(tvGetCode).accept(true);
//                        RxTextView.text(tvGetCode).accept("获取验证码");
//                    } else {
//                        RxTextView.text(tvGetCode).accept("重新发送(" + aLong + ")s");
//                    }
//                });


        //验证输入内容
        Observable<CharSequence> phoneObservale = RxTextView.textChanges(etPhone).debounce(500, TimeUnit.MILLISECONDS);
        Observable<CharSequence> pswObservale = RxTextView.textChanges(etPsw).debounce(500, TimeUnit.MILLISECONDS);
        Observable<CharSequence> codeObservale = RxTextView.textChanges(etCode).debounce(500, TimeUnit.MILLISECONDS);
        Observable<CharSequence> usernameObservale = RxTextView.textChanges(etUsername).debounce(500, TimeUnit.MILLISECONDS);
        Observable.combineLatest(phoneObservale, codeObservale, usernameObservale, pswObservale, new Function4<CharSequence, CharSequence, CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence phone, CharSequence code, CharSequence username, CharSequence psw) throws Exception {
                boolean isPhpne = RegexUtils.isMobileExact(phone.toString());
                boolean isPSW = psw.toString().length() >= 6;
                boolean isCode = code.toString().length() > 0;
                boolean isUsername = username.toString().length() > 0;
                if (isUserName) {
                    return isPSW && isUsername;
                } else {
                    return isPhpne && isCode;
                }
            }
        }).compose(bindToLife())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> RxView.enabled(tvLogin).accept(aBoolean));

        //登录监听
        RxView.clicks(tvLogin)
                .throttleFirst(2, TimeUnit.SECONDS)
                .compose(bindToLife())
                .subscribe(o -> {
                    if (isUserName) {
                        getP().login(etUsername.getText().toString().trim(), etPsw.getText().toString().trim(), isUserName);
                    } else {
                        getP().login(etPhone.getText().toString().trim(), etCode.getText().toString().trim(), isUserName);
                    }
                });
        rgLoginType.setOnCheckedChangeListener(listen);
    }

    public void loginSuccess(String msg) {
        getvDelegate().toastShort(msg);
        //极光推送设置
        getP().setPushCode(JPushInterface.getRegistrationID(context));
        if (jumpPath != null) {
            if (jumpBundle != null) {
                withValueActivity(jumpPath).withBundle(ARouterConstant.JUMP_BUNDLE, jumpBundle).navigation();
            } else {
                withValueActivity(jumpPath).navigation();
            }
        }
        finish();
    }

    public void getCodeSuccess(String msg) {
        getvDelegate().toastShort(msg);
    }

    /**
     * 登录类型切换特效初始化
     */
    private void initLoginType() {
//        showUserNameView();
        sato0.setDuration(500);
        sato1.setDuration(500);
        sato0.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (llPhone.getVisibility() == View.VISIBLE) {
                    llPhone.setAnimation(null);
                    showUserNameView();
                    llUsername.startAnimation(sato1);
                } else {
                    llUsername.setAnimation(null);
                    showPhoneView();
                    llPhone.startAnimation(sato1);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void showPhoneView() {
        llUsername.setVisibility(View.GONE);
        llPhone.setVisibility(View.VISIBLE);
        isUserName = false;
//        tvLogin.setText("密码登录");
    }

    private void showUserNameView() {
        llPhone.setVisibility(View.GONE);
        llUsername.setVisibility(View.VISIBLE);
        isUserName = true;
//        tvLogin.setText("手机号登录");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public LoginPresenter newP() {
        return new LoginPresenter();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        etPhone = findViewById(R.id.et_phone);
        etCode = findViewById(R.id.et_code);
        etUsername = findViewById(R.id.et_username);
        etPsw = findViewById(R.id.et_psw);
        cbPwd = findViewById(R.id.cb_pwd);

        initWidget();
        initLoginType();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mTimerHelper) mTimerHelper.cancel();
    }
//
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            //与上次点击返回键时刻作差
//            if ((System.currentTimeMillis() - mExitTime) > 2000) {
//                //大于2000ms则认为是误操作，使用Toast进行提示
//                getvDelegate().toastShort("再按一次退出程序");
//                //并记录下本次点击“返回键”的时刻，以便下次进行判断
//                mExitTime = System.currentTimeMillis();
//            } else {
//                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
//                System.exit(0);
//            }
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }
}
